import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isFunction from "lodash/isFunction";
import _isEmpty from "lodash/isEmpty";
var _excluded = ["bucketName", "bucketDirectory", "viewOnly", "icon", "filesNumber", "showFilesNumber", "hasTemplate", "multiple", "btnText", "description", "onChange", "tenantId", "btnProps", "title", "docType", "storageCode"];

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _dec9, _class;

import React, { PureComponent } from 'react';
import { Alert, Button, Icon, Modal, Spin, Tag } from 'antd';
import { Bind } from 'lodash-decorators';
import Viewer from 'react-viewer';
import 'react-viewer/dist/index.css';
import intl from "../../utils/intl";
import { getEnvConfig } from "../../utils/iocUtils";
import { getAttachmentUrl, getCurrentOrganizationId, getResponse, isTenantRoleLevel } from "../../utils/utils";
import { queryFileList, queryUUID, removeFile as _removeFile } from "../../services/api";
import UploadButton from "./UploadButton";
var DEFAULT_BUCKET_NAME = 'spfm-comp'; // const previewModalStyle = {
//   maxWidth: '50vw',
//   maxHeight: '50vh',
// };
// const previewImageStyle = {
//   maxWidth: '100%',
//   maxHeight: '100%',
// };

/**
 * 使用UUID上传组件
 * @extends {Component} - React.Component
 * @reactProps {?String} bucketName - 附件桶
 * @reactProps {?String} bucketDirectory - 目录名称
 * @reactProps {?Object} attachmentUUID - 传入的UUID，如果不传入，组件可生成
 * @reactProps {?Object} currentData - 当前行数据
 * @reactProps {?function} afterOpenUploadModal - 展开modal后触发的方法
 * @reactProps {?Boolean} hasTemplate - 是否有附件模版
 * @reactProps {?String} templateAttachmentUUID - 附件模版UUID,通过 Tooltip 提示用户附件模版
 * @reactProps {?function} removeCallback - 删除文件后回调
 * @reactProps {?function} onCloseUploadModal - 关闭弹框时调用方法
 * @reactProps {?Boolean} viewOnly - 是否只读
 * @return React.element
 */

var Upload = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec9 = Bind(), (_class = /*#__PURE__*/function (_PureComponent) {
  _inherits(Upload, _PureComponent);

  var _super = _createSuper(Upload);

  function Upload(props) {
    var _this;

    _classCallCheck(this, Upload);

    _this = _super.call(this, props);
    _this.upload = void 0;
    _this.state = {
      visible: false,
      loading: false,
      modalLoading: false,
      templateList: [],
      fileList: [],
      previewVisible: false,
      previewImages: [],
      attachmentUUID: ''
    };
    _this.config = getEnvConfig();
    return _this;
  }

  _createClass(Upload, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      var _this$props = this.props,
          _this$props$bucketNam = _this$props.bucketName,
          bucketName = _this$props$bucketNam === void 0 ? DEFAULT_BUCKET_NAME : _this$props$bucketNam,
          attachmentUUID = _this$props.attachmentUUID,
          tenantId = _this$props.tenantId;

      if (attachmentUUID) {
        queryFileList({
          tenantId: tenantId,
          bucketName: bucketName,
          attachmentUUID: attachmentUUID
        }).then(function (fileList) {
          if (getResponse(fileList)) {
            _this2.setState({
              fileList: _this2.changeFileList(fileList)
            });
          }
        });
      }
    }
    /**
     * 如果attachmentUUID变化 请求新UUID中的文件列表
     * @param {Object} nextProps 下个状态的props
     */
    //  eslint-disable-next-line

  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      var _this3 = this;

      var _this$props2 = this.props,
          _this$props2$bucketNa = _this$props2.bucketName,
          bucketName = _this$props2$bucketNa === void 0 ? DEFAULT_BUCKET_NAME : _this$props2$bucketNa,
          tenantId = _this$props2.tenantId;

      if (this.props.attachmentUUID !== nextProps.attachmentUUID && nextProps.attachmentUUID) {
        queryFileList({
          tenantId: tenantId,
          bucketName: bucketName,
          attachmentUUID: nextProps.attachmentUUID
        }).then(function (fileList) {
          if (getResponse(fileList)) {
            _this3.setState({
              fileList: _this3.changeFileList(fileList)
            });
          }
        });
      }
    }
    /**
     *格式化已经上传的文件列表
     *
     * @param {*} response 请求返回的文件列表
     * @returns 格式化后的文件列表
     * @memberof UploadModal
     */

  }, {
    key: "changeFileList",
    value: function changeFileList(response) {
      var _this$props3 = this.props,
          _this$props3$bucketNa = _this$props3.bucketName,
          bucketName = _this$props3$bucketNa === void 0 ? DEFAULT_BUCKET_NAME : _this$props3$bucketNa,
          bucketDirectory = _this$props3.bucketDirectory,
          tenantId = _this$props3.tenantId;
      return response.map(function (res, index) {
        return {
          uid: index + 1,
          name: res.fileName,
          status: 'done',
          url: getAttachmentUrl(res.fileUrl, bucketName, tenantId, bucketDirectory)
        };
      });
    }
    /**
     *打开modal后返回方法，可返回当前行数据和UUID
     *
     * @memberof UploadModal
     */

  }, {
    key: "handleAfterOpenModal",
    value: function handleAfterOpenModal() {
      var _this$props4 = this.props,
          afterOpenUploadModal = _this$props4.afterOpenUploadModal,
          attachmentUUID = _this$props4.attachmentUUID;
      var stateAttachmentUUID = this.state.attachmentUUID;

      if (_isFunction(afterOpenUploadModal)) {
        afterOpenUploadModal(attachmentUUID || stateAttachmentUUID);
      }
    }
  }, {
    key: "closeUploadModal",
    value: function closeUploadModal() {
      var onCloseUploadModal = this.props.onCloseUploadModal;
      this.setState({
        visible: false
      });

      if (onCloseUploadModal) {
        onCloseUploadModal();
      }
    }
  }, {
    key: "openUploadModal",
    value: function () {
      var _openUploadModal = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
        var _this4 = this;

        var _this$props5, _this$props5$bucketNa, bucketName, attachmentUUID, templateAttachmentUUID, tenantId, stateAttachmentUUID, state, tempalteList, uuid, response, fileList;

        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                _this$props5 = this.props, _this$props5$bucketNa = _this$props5.bucketName, bucketName = _this$props5$bucketNa === void 0 ? DEFAULT_BUCKET_NAME : _this$props5$bucketNa, attachmentUUID = _this$props5.attachmentUUID, templateAttachmentUUID = _this$props5.templateAttachmentUUID, tenantId = _this$props5.tenantId;
                stateAttachmentUUID = this.state.attachmentUUID;
                this.setState({
                  visible: true,
                  loading: true
                });
                state = {
                  loading: false
                };

                if (!templateAttachmentUUID) {
                  _context.next = 9;
                  break;
                }

                _context.next = 7;
                return queryFileList({
                  tenantId: tenantId,
                  bucketName: bucketName,
                  attachmentUUID: templateAttachmentUUID
                });

              case 7:
                tempalteList = _context.sent;

                if (getResponse(tempalteList)) {
                  state = _objectSpread(_objectSpread({}, state), {}, {
                    templateList: tempalteList
                  });
                }

              case 9:
                uuid = attachmentUUID || stateAttachmentUUID;

                if (uuid) {
                  _context.next = 15;
                  break;
                }

                _context.next = 13;
                return queryUUID({
                  tenantId: tenantId
                });

              case 13:
                response = _context.sent;

                if (response) {
                  uuid = response.content;
                }

              case 15:
                state = _objectSpread(_objectSpread({}, state), {}, {
                  attachmentUUID: uuid
                });

                if (!uuid) {
                  _context.next = 22;
                  break;
                }

                _context.next = 19;
                return queryFileList({
                  tenantId: tenantId,
                  bucketName: bucketName,
                  attachmentUUID: uuid
                });

              case 19:
                fileList = _context.sent;

                if (getResponse(fileList)) {
                  state = _objectSpread(_objectSpread({}, state), {}, {
                    fileList: this.changeFileList(fileList)
                  });

                  if (this.upload) {
                    this.upload.setFileList(this.changeFileList(fileList));
                  }
                }

                this.setState(state, function () {
                  _this4.handleAfterOpenModal();
                });

              case 22:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function openUploadModal() {
        return _openUploadModal.apply(this, arguments);
      }

      return openUploadModal;
    }()
    /**
     *Ref
     *
     * @param {*} upload
     * @memberof UploadModal
     */

  }, {
    key: "onRef",
    value: function onRef(upload) {
      this.upload = upload;
    }
    /**
     *上传成功后调用方法
     *
     * @param {*} file 文件信息
     * @param {*} fileList 文件列表
     * @memberof UploadModal
     */

  }, {
    key: "onUploadSuccess",
    value: function onUploadSuccess(file, fileList) {
      var uploadSuccess = this.props.uploadSuccess;

      if (uploadSuccess) {
        uploadSuccess();
      }

      this.setState({
        fileList: fileList
      });
      var onChange = this.props.onChange;

      if (onChange) {
        var single = this.props.single;

        if (single) {// 由 UploadButton 触发 onUploadSuccess
        } else {
          var attachmentUUID = this.props.attachmentUUID;
          var stateAttachmentUUID = this.state.attachmentUUID;
          onChange(attachmentUUID || stateAttachmentUUID);
        }
      }
    }
    /**
     * 图片预览
     * @param {*} file
     */

  }, {
    key: "handlePreview",
    value: function handlePreview(file) {
      this.setState({
        previewImages: [{
          src: file.url || file.thumbUrl,
          alt: '' // 由于下方会显示 alt 所以这里给空字符串 file.name,

        }],
        previewVisible: true
      });
    }
    /**
     * 图片预览取消
     */

  }, {
    key: "handlePreviewCancel",
    value: function handlePreviewCancel() {
      this.setState({
        previewImages: [],
        previewVisible: false
      });
    }
    /**
     *删除文件
     *
     * @param {*} file 文件
     * @memberof UploadModal
     */

  }, {
    key: "removeFile",
    value: function removeFile(file) {
      var _this5 = this;

      var _this$props6 = this.props,
          removeCallback = _this$props6.removeCallback,
          _this$props6$bucketNa = _this$props6.bucketName,
          bucketName = _this$props6$bucketNa === void 0 ? DEFAULT_BUCKET_NAME : _this$props6$bucketNa,
          tenantId = _this$props6.tenantId,
          attachmentUUID = _this$props6.attachmentUUID;
      var _this$state = this.state,
          stateAttachmentUUID = _this$state.attachmentUUID,
          fileList = _this$state.fileList;
      this.setState({
        modalLoading: true
      });

      if (file.url) {
        var splitDatas = file.url && file.url.split('=') || [];
        var fileUrl = splitDatas[splitDatas.length - 1];
        return _removeFile({
          tenantId: tenantId,
          bucketName: bucketName,
          attachmentUUID: attachmentUUID || stateAttachmentUUID,
          urls: [fileUrl]
        }).then(function (res) {
          if (getResponse(res)) {
            _this5.setState({
              modalLoading: false,
              fileList: fileList.filter(function (list) {
                return list.url !== file.url;
              })
            });

            if (removeCallback) {
              removeCallback();
            }

            return true;
          }

          _this5.setState({
            modalLoading: false
          });

          return false;
        });
      }

      this.setState({
        modalLoading: false,
        fileList: fileList.filter(function (list) {
          return list.uid !== file.uid;
        })
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props7 = this.props,
          _this$props7$bucketNa = _this$props7.bucketName,
          bucketName = _this$props7$bucketNa === void 0 ? DEFAULT_BUCKET_NAME : _this$props7$bucketNa,
          bucketDirectory = _this$props7.bucketDirectory,
          _this$props7$viewOnly = _this$props7.viewOnly,
          viewOnly = _this$props7$viewOnly === void 0 ? false : _this$props7$viewOnly,
          _this$props7$icon = _this$props7.icon,
          icon = _this$props7$icon === void 0 ? viewOnly ? 'paper-clip' : 'upload' : _this$props7$icon,
          _this$props7$filesNum = _this$props7.filesNumber,
          filesNumber = _this$props7$filesNum === void 0 ? '' : _this$props7$filesNum,
          _this$props7$showFile = _this$props7.showFilesNumber,
          showFilesNumber = _this$props7$showFile === void 0 ? true : _this$props7$showFile,
          hasTemplate = _this$props7.hasTemplate,
          _this$props7$multiple = _this$props7.multiple,
          multiple = _this$props7$multiple === void 0 ? true : _this$props7$multiple,
          _this$props7$btnText = _this$props7.btnText,
          btnText = _this$props7$btnText === void 0 ? viewOnly ? intl.get('cpaas.common.upload.view').d('查看附件') : intl.get('cpaas.common.upload.text').d('上传附件') : _this$props7$btnText,
          description = _this$props7.description,
          onChange = _this$props7.onChange,
          tenantId = _this$props7.tenantId,
          _this$props7$btnProps = _this$props7.btnProps,
          btnProps = _this$props7$btnProps === void 0 ? {} : _this$props7$btnProps,
          _this$props7$title = _this$props7.title,
          title = _this$props7$title === void 0 ? intl.get('cpaas.common.upload.modal.title').d('附件') : _this$props7$title,
          docType = _this$props7.docType,
          storageCode = _this$props7.storageCode,
          otherProps = _objectWithoutProperties(_this$props7, _excluded);

      var attachmentUUID = this.props.attachmentUUID;
      var _this$state2 = this.state,
          visible = _this$state2.visible,
          modalLoading = _this$state2.modalLoading,
          previewVisible = _this$state2.previewVisible,
          previewImages = _this$state2.previewImages,
          fileList = _this$state2.fileList,
          _this$state2$template = _this$state2.templateList,
          templateList = _this$state2$template === void 0 ? [] : _this$state2$template,
          _this$state2$loading = _this$state2.loading,
          loading = _this$state2$loading === void 0 ? false : _this$state2$loading,
          stateAttachmentUUID = _this$state2.attachmentUUID;
      var CPAAS_FILE = this.config.CPAAS_FILE;
      var actionPathname = isTenantRoleLevel() ? "".concat(CPAAS_FILE, "/v1/").concat(getCurrentOrganizationId(), "/files/attachment/multipart") : "".concat(CPAAS_FILE, "/v1/files/attachment/multipart");
      var action = "".concat(actionPathname);
      var uploadLinkButton = /*#__PURE__*/React.createElement(React.Fragment, null, _isEmpty(btnProps) ? /*#__PURE__*/React.createElement("a", {
        onClick: this.openUploadModal
      }, icon && /*#__PURE__*/React.createElement(Icon, {
        type: icon
      }), btnText) : /*#__PURE__*/React.createElement(Button, Object.assign({
        onClick: this.openUploadModal
      }, btnProps), btnText), showFilesNumber && (filesNumber && filesNumber !== 0 || fileList.length > 0) && /*#__PURE__*/React.createElement(Tag, {
        color: "#108ee9",
        style: {
          height: 'auto',
          lineHeight: '15px',
          marginLeft: '4px'
        }
      }, filesNumber && filesNumber !== 0 ? filesNumber : fileList.length));
      var descriptionBlock = null;

      if (hasTemplate || description) {
        var templateLinks = templateList.map(function (tpl) {
          return /*#__PURE__*/React.createElement(Tag, null, /*#__PURE__*/React.createElement("a", {
            style: {
              color: '#108ee9'
            },
            href: tpl.fileUrl,
            target: "_blank",
            rel: "noopener noreferrer"
          }, tpl.fileName));
        });
        var message = /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", null, description), /*#__PURE__*/React.createElement("div", null, hasTemplate && /*#__PURE__*/React.createElement("span", null, intl.get('cpaas.common.upload.template').d('附件模板'), ": ", templateLinks)));
        descriptionBlock = /*#__PURE__*/React.createElement(Alert, {
          showIcon: true,
          message: message,
          style: {
            marginRight: '8px',
            marginBottom: '15px'
          },
          type: "info"
        });
      }

      var modalContent = /*#__PURE__*/React.createElement(React.Fragment, null, loading && /*#__PURE__*/React.createElement("div", {
        style: {
          textAlign: 'center',
          padding: '30px 50px'
        }
      }, /*#__PURE__*/React.createElement(Spin, null)), /*#__PURE__*/React.createElement("div", {
        style: {
          display: loading ? 'none' : ''
        }
      }, descriptionBlock, /*#__PURE__*/React.createElement(Spin, {
        spinning: modalLoading
      }, /*#__PURE__*/React.createElement(UploadButton, Object.assign({
        viewOnly: viewOnly,
        multiple: multiple,
        listType: "picture-card",
        onPreview: this.handlePreview,
        bucketName: bucketName,
        bucketDirectory: bucketDirectory,
        onRef: this.onRef,
        tenantId: tenantId,
        onRemove: this.removeFile,
        onUploadSuccess: this.onUploadSuccess,
        showUploadList: {
          removePopConfirmTitle: intl.get('cpaas.common.message.confirm.delete').d('是否删除此条记录？'),
          showRemoveIcon: !viewOnly
        },
        action: action
      }, otherProps, {
        attachmentUUID: attachmentUUID || stateAttachmentUUID
      })))));
      return /*#__PURE__*/React.createElement(React.Fragment, null, uploadLinkButton, /*#__PURE__*/React.createElement(Modal, {
        visible: visible,
        title: title,
        width: 610,
        footer: null,
        onCancel: this.closeUploadModal
      }, modalContent), /*#__PURE__*/React.createElement(Viewer, {
        noImgDetails: true,
        noNavbar: true,
        scalable: false,
        changeable: false,
        visible: previewVisible,
        onClose: this.handlePreviewCancel,
        images: previewImages
      }));
    }
  }]);

  return Upload;
}(PureComponent), (_applyDecoratedDescriptor(_class.prototype, "changeFileList", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "changeFileList"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleAfterOpenModal", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleAfterOpenModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "closeUploadModal", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "closeUploadModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "openUploadModal", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "openUploadModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onRef", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "onRef"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "onUploadSuccess", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "onUploadSuccess"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handlePreview", [_dec7], Object.getOwnPropertyDescriptor(_class.prototype, "handlePreview"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handlePreviewCancel", [_dec8], Object.getOwnPropertyDescriptor(_class.prototype, "handlePreviewCancel"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "removeFile", [_dec9], Object.getOwnPropertyDescriptor(_class.prototype, "removeFile"), _class.prototype)), _class));
export { Upload as default };